Hey, A few days ago I had post this : HOW TO: Using sorting on GridView without a DataSourceControl, but it was explaining how make this using DataTable as a datasource. I was doing something in a project, when suddenly 🙂 I need to sort a gridview columns, but my datasource was a ListColletion, like this: List<Costumer>, I made a research found out different ways to make the sort works. But the simplest way is this one:
private string ConvertSortDirectionToSql(SortDirection sortDirection) { string newSortDirection = string.Empty; switch (sortDirection) { case SortDirection.Ascending: newSortDirection = "ASC"; break; case SortDirection.Descending: newSortDirection = "DESC"; break; } return newSortDirection; } protected void GridView_Sorting(object sender, GridViewSortEventArgs e) { string previousSortExpression=(string)ViewState["previousGVSortKey"]; string sortExpression=e.SortExpression; SortDirection sortDirection = e.SortDirection; if (sortExpression.Equals(previousSortExpression)) { sortDirection = SortDirection.Descending; ViewState["previousGVSortKey"] = string.Empty; } else { ViewState["previousGVSortKey"] = sortExpression; } List<Costumer> list = (List<Costumer>)GridView.DataSource; if (list.Count > 0) { var query = from c in list select c; if (sortDirection == SortDirection.Ascending) { if (sortExpression == "FIRST_NAME") query=query.OrderBy(c => c.FirstName); if (sortExpression == "LAST_NAME") query=query.OrderBy(c => c.LastName); if (sortExpression == "EMAIL") query = query.OrderBy(c => c.Email); if (sortExpression == "ADDRESS") query = query.OrderBy(c => c.Address); } else { if (sortExpression == "FIRST_NAME") query = query.OrderByDescending(c => c.FirstName); if (sortExpression == "LAST_NAME") query = query.OrderByDescending(c => c.LastName); if (sortExpression == "EMAIL") query = query.OrderByDescending(c => c.Email); if (sortExpression == "ADDRESS") query = query.OrderByDescending(c => c.Address); } GridView.DataSource = query.ToList(); GridView.DataBind(); } }
I know there are a lot of better way to do that, but for now it is working, maybe I’ll try to make something better.
One thought on “HOW TO: Sort a GridView using List as a datasource”